package servlet;

import java.io.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import to.OrdenPedidoTO;
import to.DetallePedidoTO;

@SuppressWarnings("serial")
public class ActualizarCarritoPedido extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        procesar(req, resp);
    }
    
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        procesar(req, resp);
    }

    private void procesar(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession sesion = req.getSession();
        OrdenPedidoTO to;
        try {
            if (sesion.getAttribute("carritoPedidos") != null) {
                to = (OrdenPedidoTO) sesion.getAttribute("carritoPedidos");
                for (int i = 0; i < to.getList().size(); i++) {
                    DetallePedidoTO detalle = (DetallePedidoTO) to.getList().get(i);
                    String productoID = String.valueOf(detalle.getCProducto());
                    String unidades = req.getParameter(productoID);
                    if(unidades != null){
                        detalle.setNCantidad(Integer.parseInt(unidades));
                        detalle.setIDescuento((detalle.getIPrecio()*detalle.getNCantidad())*(detalle.getProductoTO().getPDescuento()/100));
                    }
                }
                getServletContext().getRequestDispatcher("/Registro_Pedido.jsp").forward(req, resp);
            }
        }
        catch (Exception e) {
            PrintWriter out = resp.getWriter();
            out.println("<HTML>");
            out.println("<HEAD>");
            out.println("</HEAD>");
            out.println("<BODY>");

            String msg = (String) e.getMessage();
            out.println("<P>" + msg + "</P>");

            out.println("</BODY>");
            out.println("</HTML>");
	}
    }
}